#!/usr/bin/python
# -*- coding: utf-8 -*-

#备份文件本机保存5天，5天后自动删除。
import os
import sys
import zipfile
import socket
import commands
from datetime import date,datetime,timedelta
from ftplib import FTP

########指定配置文件目录#########
website_dir='/data/www/zabbix'  #网站目录
backup_dir='/data/backup/zabbix'   #本地的备份目录（即要把备份文件放在哪里）
file_owner='172.16.1.11_zabbix.aishangwei.net'
ftp_server='172.16.1.10'    #远程FTP服务器地址
ftp_user='test1'    #远程FTP用户名
ftp_password='test1!'    #远程FTP密码
ftp_backup_dir='backup'    #远程FTP上要用于备份的目录
##################################

print("checking backup directory...")
try:
    if os.path.isdir(backup_dir):
        print("found backup directory " + backup_dir + ", ready to process backup...")
    else:
        print("don't found backup directory " + backup_dir + ", try to build one...")
        os.mkdir(backup_dir)
except IOError, err:
    print err
    sys.exit()

	
newday = date.today()    #获取今天的日期
oldday = date.today()-timedelta(6335)    #获得5天前的日期
newfile = backup_dir + '/' + file_owner + '_backup_data_' + str(newday.year) + '.' + str(newday.month) + '.' +  str(newday.day) + '.zip'    #本次备份的文件名(绝对路径)
oldfile = backup_dir + '/' + file_owner + '_backup_data_' + str(oldday.year) + '.' + str(oldday.month) + '.' +  str(oldday.day) + '.zip'    #5天前备份的文件名(绝对路径)
  
print("today is " + str(newday.year) + "." + str(newday.month) + "." +  str(newday.day))

print("delete old backup data...")    #删除本机上5天前的备份文件
try:
    if os.path.isfile(oldfile):
        os.remove(oldfile)
        print("found old data at local, deleted it.")
    else:
        print("doesn't found old data at local, jumped.")
except IOError, err:
    print err
    sys.exit()

print("compress your website directory...")    #压缩网站目录
try:
    f = zipfile.ZipFile(newfile,'w',zipfile.ZIP_DEFLATED)
    for dirpath, dirnames, filenames in os.walk(website_dir):
        for filename in filenames:
            f.write(os.path.join(dirpath,filename))
    f.close()
    print("compressed webiste directory completely! file name is " + newfile)
except IOError, err:
    print err
    sys.exit()
def upload():
    socket.setdefaulttimeout(60)    #超时FTP时间设置为60秒
    ftp = FTP(ftp_server)
    print("login ftp...")
    try:
        ftp.login(ftp_user, ftp_password)    #登陆FTP
        print(ftp.getwelcome().decode("GB2312").encode("UTF-8"))   #获得欢迎信息

        try:
            if ftp_backup_dir in ftp.nlst():
                print("found backup folder in ftp server, upload processing.")
            else:
                print("doesn't found backup folder in ftp server, try to build it.")
                ftp.mkd(ftp_backup_dir)
        except:
            print("the folder " + ftp_backup_dir + " doesn't exist and can't be create!")
            sys.exit()
    except:
        print("ftp login failed. exit.")
        sys.exit()
    ftp.cwd(ftp_backup_dir)    #设置FTP路径

    print("upload data...")
    try:
        ftp.storbinary('STOR ' + os.path.basename(newfile), open(newfile,'rb'), 1024)  #上传备份文件
    except:
        print("upload failed. check your permission.")
        sys.exit()
   
    print("delete old file...")
    if os.path.basename(oldfile) in ftp.nlst():
        ftp.delete(os.path.basename(oldfile))    #删除5天前的备份文件
        print("found old data file at ftp server, deleted it.")
    else:
        print("doesn't found old file at ftp server, jumped.")
    print("ftp upload successful. exit...")
    ftp.quit()

if __name__== '__main__':
    upload()
